package com.sne.sys.controller;


import com.sne.common.entity.Result;
import com.sne.common.validated.Insert;
import com.sne.common.validated.Update;
import com.sne.sys.entity.SysDept;
import com.sne.sys.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * <p>
 * 部门 前端控制器
 * </p>
 *
 * @author fanghh
 * @since 2020-01-03
 */
@Validated
@RestController
@RequestMapping("/sys/sys-dept")
@Api(tags = "部门管理")
public class SysDeptController {

    @Autowired
    private ISysDeptService iSysDeptService;

    @ApiOperation(value = "查找部门树")
    @GetMapping("/tree")
    public Result findTree() {
        return Result.success(iSysDeptService.findTree());
    }

    @ApiOperation(value = "根据id获取部门")
    @GetMapping("/find/{id}")
    public Result find(@PathVariable Long id) {
        return Result.success(iSysDeptService.getById(id));
    }

    @PreAuthorize("hasAuthority('sys:dept:save')")
    @ApiOperation(value = "保存部门")
    @PostMapping("/save")
    public Result save(@Validated({Insert.class}) @RequestBody SysDept sysDept) {
        return Result.success(iSysDeptService.save(sysDept));
    }

    @PreAuthorize("hasAuthority('sys:dept:update')")
    @ApiOperation(value = "更新部门")
    @PutMapping("/update")
    public Result update(@Validated({Update.class}) @RequestBody SysDept sysDept) {
        return Result.success(iSysDeptService.updateById(sysDept));
    }

    @PreAuthorize("hasAuthority('sys:dept:delete')")
    @ApiOperation(value = "删除部门")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return Result.success(iSysDeptService.deleteByDeptId(id));
    }

    @PreAuthorize("hasAuthority('sys:dept:deleteIds')")
    @ApiOperation(value = "删除多个部门")
    @DeleteMapping("/deleteIds")
    public Result deleteIds(@RequestBody @Size(min = 1,message = "ids不能为空") List<Long> ids) {
        return Result.success(iSysDeptService.deleteByDeptIds(ids));
    }

    @PreAuthorize("hasAuthority('sys:dept:list')")
    @ApiOperation(value = "获取部门列表")
    @PostMapping("/list")
    public Result list(@RequestBody SysDept dept){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return Result.success(iSysDeptService.findList(dept));
    }
}

